package com.example.gouwu2;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;
public class HomeAdapter extends BaseAdapter {

    private Context context;
    // 商品数据列表
    private List<HomeItem> itemList;

    //构造函数
    public HomeAdapter(Context context, List<HomeItem> itemList) {
        this.context = context;
        this.itemList = itemList;
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public Object getItem(int position) {
        return itemList.get(position);
    }


    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ViewHolder holder;

        //  视图复用检查
        if (convertView == null) {

            convertView = LayoutInflater.from(context).inflate(R.layout.item_home, parent, false);

            // 初始化ViewHolder
            holder = new ViewHolder();
            holder.imageView = convertView.findViewById(R.id.item_img);
            holder.titleView = convertView.findViewById(R.id.item_title);
            holder.priceView = convertView.findViewById(R.id.item_price);

            // 将ViewHolder存储在视图中
            convertView.setTag(holder);
        } else {
            // 重用已有视图：从tag中获取ViewHolder
            holder = (ViewHolder) convertView.getTag();
        }

        //获取当前商品数据
        HomeItem item = itemList.get(position);

        // 绑定数据到视图
        holder.imageView.setImageResource(item.getImageRes());
        holder.titleView.setText(item.getTitle());
        holder.priceView.setText("¥" + item.getPrice());

        return convertView;
    }


     //更新适配器数据
    public void updateData(List<HomeItem> newList) {
        this.itemList = newList;        // 更新数据源
        notifyDataSetChanged();         // 通知ListView刷新显示
    }
    static class ViewHolder {
        ImageView imageView;
        TextView titleView;
        TextView priceView;
    }
}